// 文件：src/ch09/graph-basic.ts
import { StateGraph } from "@langchain/langgraph";
import { RagState } from "./state";
import { retrieveNode, fuseNode, answerNode, guardNode, feedbackNode } from "./node";

export async function buildRagGraph() {
  const graph = new StateGraph<RagState>({
    channels: {
      question: { value: "" },
      retriever: { value: "topk" },
      hits: { value: [] },
      retrievedDocs: { value: [] }, // 添加缺失的字段
      fused: { value: [] },
      answer: { value: { answer: "", citations: [], confidence: 0 } },
      feedback: { value: {} },
      logs: { value: [], merge: (prev, next) => [...prev, ...next] },
      error: { value: "" },
    },
  });

  graph.addNode("retrieve", retrieveNode);
  graph.addNode("fuse", fuseNode);
  graph.addNode("answer", answerNode);
  graph.addNode("guard", guardNode);
  graph.addNode("feedback", feedbackNode);

  graph.addEdge("start", "retrieve");
  graph.addEdge("retrieve", "fuse");
  graph.addEdge("fuse", "answer");
  graph.addEdge("answer", "guard");

  // 条件：若 guard 有错误 → end（或者可以重试）；否则进入 feedback
  graph.addConditionalEdges("guard", (s) => (s.error ? "end" : "feedback"), {
    end: "end",
    feedback: "feedback",
  });

  graph.addEdge("feedback", "end");

  return graph.compile();
}